package com.fa4j.app.gateway;

import org.springdoc.core.properties.AbstractSwaggerUiConfigProperties;
import org.springdoc.core.properties.SwaggerUiConfigProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.context.annotation.Bean;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static org.springdoc.core.utils.Constants.DEFAULT_API_DOCS_URL;


@EnableDiscoveryClient
@SpringBootApplication
public class GatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }


    @Bean
    @ConditionalOnProperty(name = "springdoc.api-docs.enabled", havingValue = "true")
    public Set<AbstractSwaggerUiConfigProperties.SwaggerUrl> apis(RouteDefinitionLocator locator, SwaggerUiConfigProperties swaggerUiConfigProperties) {
        Set<AbstractSwaggerUiConfigProperties.SwaggerUrl> urls = new HashSet<>();
        List<RouteDefinition> definitions = locator.getRouteDefinitions().collectList().block();
        if (definitions == null) {
            return urls;
        }
        for (RouteDefinition definition : definitions) {
            for (PredicateDefinition predicate : definition.getPredicates()) {
                if ("Path".equals(predicate.getName())) {
                    for (String path : predicate.getArgs().values()) {
                        int apiPathIndex = path.indexOf(DEFAULT_API_DOCS_URL);
                        if (apiPathIndex != -1) {
                            String groupName = definition.getId();
                            if ((apiPathIndex + DEFAULT_API_DOCS_URL.length()) < path.length()) {
                                groupName += path.substring(apiPathIndex + DEFAULT_API_DOCS_URL.length());
                            }
                            AbstractSwaggerUiConfigProperties.SwaggerUrl swaggerUrl = new AbstractSwaggerUiConfigProperties.SwaggerUrl(groupName, path, null);
                            urls.add(swaggerUrl);
                        }
                    }
                }
            }

        }
        swaggerUiConfigProperties.setUrls(urls);
        return urls;
    }
}
